<div class="budget-container">
  <!-- 顶部菜单栏 -->
  <div class="budget-header" style="display: flex;align-items: center;">
    <div class="layui-btn-group" style="display: flex;align-items: center;">
      <button class="layui-btn" id="btn-open">打开结算</button>
      <button class="layui-btn layui-disabled" id="btn-export" disabled>导出结算</button>
      <button class="layui-btn layui-disabled" id="btn-file" disabled>结算存档</button>
    </div>
  </div>

  <!-- 项目概览div布局 - 初始隐藏 -->
  <div class="budget-overview layui-hide" id="project-overview">
    <div class="layui-card">
      <div class="layui-card-body">

        <!-- 项目名称 -->
        <div class="layui-row layui-col-space15">
          <div class="layui-col-md1 project-row-title">项目名称</div>
          <div class="layui-col-md8 project-data-display" id="project-name"></div>
        </div>
        <!-- 项目编码 -->
        <div class="layui-row layui-col-space15">
          <div class="layui-col-md1 project-row-title">设计编码</div>
          <div class="layui-col-md2 project-data-display" id="design-code"></div>
          <div class="layui-col-md1 project-label-cell">立项编码</div>
          <div class="layui-col-md2 project-data-display" id="approval-code"></div>
          <div class="layui-col-md5 edit-button-column">
            <button type="button" class="layui-btn layui-btn-primary  layui-border-green" id="btn-edit-approval">
              <i class="layui-icon layui-icon-edit"></i>立项信息
            </button>
          </div>
        </div>

        <!-- 项目概述 -->
        <div class="layui-row layui-col-space15 project-description-row">
          <div class="layui-col-md1 project-row-title">项目概述</div>
          <div class="layui-col-md10 project-data-display" id="project-description"></div>
        </div>

        <!-- 人工数量 -->
        <div class="layui-row layui-col-space15">
          <div class="layui-col-md1 project-row-title">人工设计</div>
          <div class="layui-col-md1 project-label-cell">技工工日</div>
          <div class="layui-col-md1 project-data-display" id="mechanic"></div>

          <div class="layui-col-md1 project-label-cell">普工工日</div>
          <div class="layui-col-md1 project-data-display" id="general"></div>

          <div class="layui-col-md1 project-label-cell">机械台班</div>
          <div class="layui-col-md1 project-data-display" id="machine"></div>

          <div class="layui-col-md1 project-label-cell">仪器仪表</div>
          <div class="layui-col-md1 project-data-display" id="instrument"></div>

          <div class="layui-col-md2 edit-button-column">
            <button type="button" class="layui-btn layui-btn-primary layui-border-green" id="btn-edit-labor">
              <i class="layui-icon layui-icon-edit"></i>人工明细
            </button>
          </div>
        </div>

        <!-- 材料数量 -->
        <div class="layui-row layui-col-space15">
          <div class="layui-col-md1 project-row-title">材料设计</div>
          <div class="layui-col-md1 project-label-cell">种类合计</div>
          <div class="layui-col-md1 project-data-display" id="material-type"></div>

          <div class="layui-col-md1 project-label-cell">金额合计</div>
          <div class="layui-col-md1 project-data-display" id="material-amount"></div>

          <div class="layui-col-md6 edit-button-column">
            <button type="button" class="layui-btn  layui-disabled layui-hide" id="btn-get-balance" disabled>
              <i class="layui-icon layui-icon-table"></i>工程库存
            </button>
            <button type="button" class="layui-btn layui-disabled layui-hide" id="btn-get-outbound" disabled>
              <i class="layui-icon layui-icon-table"></i>出库信息
            </button>
            <button type="button" class="layui-btn layui-btn-primary layui-border-green" id="btn-edit-material">
              <i class="layui-icon layui-icon-edit"></i>材料明细
            </button>
          </div>
        </div>

        <!-- 其它费用 -->
        <div class="layui-row layui-col-space15">
          <div class="layui-col-md1 project-row-title">其它费用</div>
          <div class="layui-col-md2 project-data-display" id="other-amount"
            style="display: inline-block;text-align: right;padding-top: 10px;"></div>
          <div class="layui-col-md8 edit-button-column">
            <button type="button" class="layui-btn layui-btn-primary layui-border-green" id="btn-edit-other">
              <i class="layui-icon layui-icon-edit"></i>费用明细
            </button>
          </div>
        </div>

        <!-- 结转金额 -->
        <div class="layui-row layui-col-space15">
          <div class="layui-col-md1 project-row-title">结转金额</div>
          <div class="layui-col-md2 project-data-display" id="carry-over"
            style="display: inline-block;text-align: right;padding-top: 10px;"></div>
        </div>

        <!-- 结算人工 -->
        <div class="layui-row layui-col-space15">
          <div class="layui-col-md1 project-row-title">结算人工</div>
          <div class="layui-col-md2 project-data-display" id="settlement-labor"
            style="display: inline-block;text-align: right;padding-top: 10px;">
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 底部状态栏 -->
  <div class="budget-footer">
    <div></div>
  </div>
</div>

<script>
  layui.use(['table', 'element', 'layer', 'form'], function () {
    var table = layui.table;
    var element = layui.element;
    var layer = layui.layer;
    var form = layui.form;
    var $ = layui.$;
    var bsm_utils = layui.bsm_utils;

    var DesignType = API_CONFIG.DESIGNTYPE.Settlement;  //结算
    var isFiled = false; // 项目是否已存档

    var isReadonly = false; //项目内容是否可编辑

    var userRole = API_CONFIG.ROLE.Client; // 初始化用户等级为普通用户
    if (checkUserRole(API_CONFIG.ROLE.Accepter)) {
      userRole = API_CONFIG.ROLE.Accepter;
      isReadonly = false;
    }

    // 当前项目数据
    var currentProject = null;
    // 存储打开的弹出层引用
    var openLayers = {};

    // 默认弹窗尺寸
    var defaultPopupSize = {
      width: '800px',
      height: '600px'
    };

    // 初始化页面
    function initPage() {
      toggleButtons(false);
      form.render();
    }

    // 更新项目状态显示，特别是按钮可用状态
    function updateProjectStatus() {
      // 如果有打开的项目，导出按钮可用
      if (currentProject) {
        $('#btn-export').removeClass('layui-disabled').prop('disabled', false);
        if (isFiled) {
          $('#btn-file').addClass('layui-disabled').prop('disabled', true);
          // $('#btn-edit-labor').addClass('layui-disabled').prop('disabled', true);
          // $('#btn-edit-material').addClass('layui-disabled').prop('disabled', true);
          // $('#btn-edit-other').addClass('layui-disabled').prop('disabled', true);
        } else {
          $('#btn-file').removeClass('layui-disabled').prop('disabled', false);
          // $('#btn-edit-labor').removeClass('layui-disabled').prop('disabled', false);
          // $('#btn-edit-material').removeClass('layui-disabled').prop('disabled', false);
          // $('#btn-edit-other').removeClass('layui-disabled').prop('disabled', false);
        }
        $('#project-overview').removeClass('layui-hide');
      } else {
        $('#btn-file, #btn-export').addClass('layui-disabled').prop('disabled', true);
        $('#project-overview').addClass('layui-hide');
      }
    }

    // 切换按钮状态
    function toggleButtons(enable) {
      $('#btn-file, #btn-export').toggleClass('layui-disabled', !enable).prop('disabled', !enable);
      if (userRole !== API_CONFIG.ROLE.Designer) {
        $('#btn-new').addClass('layui-disabled').prop('disabled', true);
      }
    }

    // 加载项目数据到UI
    function loadProjectData(projectData) {
      if (!projectData) return;

      currentProject = projectData;
      isFiled = projectData.filed || false;
      if (isFiled) {
        isReadonly = true;
      } else if (userRole === API_CONFIG.ROLE.Designer) {
        isReadonly = false;
      }

      // 基本信息
      $('#project-name').text(projectData.name || '');
      $('#design-code').text(projectData.design_code || '');
      $('#approval-code').text(projectData.approval_code || '');
      $('#project-description').text(projectData.project_overview || '');

      // 人工数量 - 添加number-cell类并格式化
      $('#mechanic').text(formatNumber(projectData.mechanic)).addClass('number-cell');
      $('#general').text(formatNumber(projectData.general)).addClass('number-cell');
      $('#machine').text(formatNumber(projectData.machine)).addClass('number-cell');
      $('#instrument').text(formatNumber(projectData.instrument)).addClass('number-cell');

      // 材料数量
      $('#material-type').text(projectData.material_type_count || '');
      $('#material-amount').text(formatNumber(projectData.material_amount)).addClass('number-cell');

      // 其他信息
      $('#other-amount').text(formatNumber(projectData.other_money)).addClass('number-cell');
      $('#carry-over').text(formatNumber(projectData.fixed_asset)).addClass('number-cell');
      $('#settlement-labor').text(formatNumber(projectData.labor_cost)).addClass('number-cell');

      updateProjectStatus();
    }

    // 数字格式化函数
    function formatNumber(value) {
      const num = Number(value) || 0;
      return num.toFixed(2);
    }

    function updateProjectBase(baseData) {
      if (!baseData) return;

      // 基本信息
      $('#design-code').text(baseData.design_code || '');
      $('#project-name').text(baseData.name || '');
      $('#project-description').text(baseData.project_overview || '');

      updateProjectStatus();
    }

    // 全局回调函数 - 处理新建项目
    window.handleProjectBase = function (projectData) {
      if (!projectData || !projectData.design_code) {
        layer.msg('项目数据无效', { icon: 2 });
        return;
      }
      currentProject = {
        design_code: projectData.design_code,
        name: projectData.name,
        project_overview: projectData.description || ''
      };

      // loadProjectData(currentProject);
      updateProjectBase(currentProject);

      if (projectData.isEdit) {
        layer.msg('项目保存成功', { icon: 1 });
      } else {
        layer.msg('项目创建成功', { icon: 1 });
      }
    };

    // 全局回调函数 - 处理打开项目
    window.handleProjectSelected = function (projectData) {
      loadProjectData(projectData);
      layer.msg('项目加载成功', { icon: 1 });
    }

    // 全局回调函数 - 更新项目摘要数据
    window.updateProjectData = function (dcode, dtype) {
      // 重新加载项目数据
      http.get(API_CONFIG.ENDPOINTS.GET_PROJECT_RESUME, {
        design_code: dcode,
        design_type: dtype
      }).then(function (res) {
        if (res.code === 0 && res.data) {
          loadProjectData(res.data);
        }
      }).catch(function (err) {
        console.error('更新项目数据失败:', err);
      });
    };

    // 绑定事件
    function bindEvents() {

      // 打开按钮
      $('#btn-open').click(function () {
        currentProject = null;
        bsm_utils.openPopup('打开项目', `/common/project_open.html?design_type=${DesignType}`, {
          width: (window.screen.width * 0.6) + 'px',
          height: (window.screen.height * 0.7) + 'px'
        });
      });

      // 导出按钮
      $('#btn-export').click(function () {
        if (!currentProject) return;
        const loading = layer.msg('正在生成方案，请稍候...', { icon: 16, shade: 0.3, time: 0 });

        http.download(API_CONFIG.ENDPOINTS.EXPORT_PROJECT, {
          design_code: currentProject.design_code,
          design_type: DesignType,
        },)// `设计方案_${currentProject.design_code}.xlsx`)
          .then(() => {
            layer.close(loading);
            layer.msg('方案下载成功', { icon: 1 });
          })
          .catch(error => {
            layer.close(loading);
            console.error('方案下载失败:', error);

            if (error.message === '网络连接失败' || error.message === '请求超时') {
              layer.msg('网络连接不稳定，请重试', { icon: 2 });
            } else {
              layer.msg('方案生成失败: ' + (error.message || '未知错误'), { icon: 2 });
            }
          });
      });

      // 存档按钮
      $('#btn-file').click(function () {
        if (!currentProject) return;
        layer.confirm('存档后项目转入结算，结算信息不再更改，是否存档？', { icon: 1 }, function (index) {
          layer.close(index);
          http.post(API_CONFIG.ENDPOINTS.FILE_PROJECT, {
            design_code: currentProject.design_code,
            project_state: API_CONFIG.PROJECT_STATE.ToAudit,
            filed: true
          }).then(function (res) {
            if (res.code === 0) {
              layer.msg('项目存档成功', { icon: 1 });
              isFiled = true;
              DesignType = API_CONFIG.DESIGNTYPE.Settlement;  //结算
              updateProjectStatus();
            } else {
              layer.msg('项目存档失败: ' + (res.msg || '未知错误'), { icon: 2 });
            }
          }).catch(function (err) {
            console.error('项目存档失败:', err);
            layer.msg('项目存档失败: ' + (err.message || '未知错误'), { icon: 2 });
          });
        });
      });

      // 编辑立项按钮
      $('#btn-edit-approval').click(function () {
        if (!currentProject) return;
        sessionStorage.setItem('designReadonly', isReadonly);
        if (isReadonly)
          url = `/common/project_base_view.html?design_code=${currentProject.design_code}&design_type=${DesignType}`;
        else
          url = `/common/project_base_edit.html?design_code=${currentProject.design_code}&design_type=${DesignType}`;
        bsm_utils.openPopup('编辑项目', url, {
          width: '800px',
          height: '620px'
        });
      });

      // 编辑人工按钮 - 使用增强的带回调函数
      $('#btn-edit-labor').click(function () {
        if (!currentProject) return;
        if(isReadonly) 
          url = `/common/project_tab3_view.html?design_code=${currentProject.design_code}&design_type=${DesignType}`;
        else
          url = `/common/project_tab3.html?design_code=${currentProject.design_code}&design_type=${DesignType}`;
        bsm_utils.openPopupWithCallback(
          '人工设计', url,
          {
            width: (window.screen.width * 0.7) + 'px',
            height: (window.screen.height * 0.7) + 'px'
          },
          function (saved) {
            if (saved) {
              // 如果保存了数据，刷新项目摘要
              window.updateProjectData(currentProject.design_code, DesignType);
              layer.msg('人工数据已保存并更新', { icon: 1 });
            }
          }
        );
      });

      // 编辑材料按钮
      $('#btn-edit-material').click(function () {
        if (!currentProject) return;
        if(isReadonly) 
          url = `/common/project_tab4_view.html?design_code=${currentProject.design_code}&design_type=${DesignType}`;
        else
          url = `/common/project_tab4.html?design_code=${currentProject.design_code}&design_type=${DesignType}`;
        bsm_utils.openPopup('材料设计', url, {
          width: (window.screen.width * 0.7) + 'px',
          height: (window.screen.height * 0.7) + 'px'
        });
      });

      // 编辑其它费用按钮
      $('#btn-edit-other').click(function () {
        if (!currentProject) return;
        if(isReadonly) 
          url = `/common/project_tab5_view.html?design_code=${currentProject.design_code}&design_type=${DesignType}`;
        else
          url = `/common/project_tab5.html?design_code=${currentProject.design_code}&design_type=${DesignType}`;
        bsm_utils.openPopup('其它费用设计', url, {
          width: (window.screen.width * 0.7) + 'px',
          height: (window.screen.height * 0.7) + 'px'
        });
      });

      $('#btn-get-balance').click(function () {
        if (!currentProject) return;
        http.post(API_CONFIG.ENDPOINTS.GET_PROJECT_BALANCE, {
          design_code: currentProject.design_code,
        }).then(function (res) {
          if (res.code === 0) {
            layer.msg('项目余额获取成功', { icon: 1 });
            isFiled = true;
            DesignType = API_CONFIG.DESIGNTYPE.Settlement;  //结算
            updateProjectStatus();
          } else {
            layer.msg('项目余额获取失败: ' + (res.msg || '未知错误'), { icon: 2 });
          }
        }).catch(function (err) {
          console.error('项目余额获取失败:', err);
          layer.msg('项目余额获取失败: ' + (err.message || '未知错误'), { icon: 2 });
        });
      });

      $('#btn-get-outbound').click(function () {
        if (!currentProject) return;
        http.post(API_CONFIG.ENDPOINTS.GET_PROJECT_OUTBOUND, {
          design_code: currentProject.design_code,
        }).then(function (res) {
          if (res.code === 0) {
            layer.msg('项目出库单获取成功', { icon: 1 });
            isFiled = true;
            DesignType = API_CONFIG.DESIGNTYPE.Settlement;  //结算
            updateProjectStatus();
          } else {
            layer.msg('项目出库单获取失败: ' + (res.msg || '未知错误'), { icon: 2 });
          }
        }).catch(function (err) {
          console.error('项目出库单获取失败:', err);
          layer.msg('项目出库单获取失败: ' + (err.message || '未知错误'), { icon: 2 });
        });
      });
    }


    function checkUserRole(role) {
      return new Promise((resolve, reject) => {
        var user = localStorage.getItem('user');
        user = JSON.parse(user);
        user_id = user.user_id;

        http.post(API_CONFIG.ENDPOINTS.CHECK_USER_ROLE, {
          user_id: user_id,
          role_id: role
        }).then(function (res) {
          if (res.code === 0) {
            resolve(res.data); // 返回成功结果
          } else {
            console.error('系统错误：无法获取用户角色:', res.msg);
            resolve(false); // 返回 false
          }
        }).catch(function (err) {
          console.error('系统异常：获取用户角色失败:', err);
          resolve(false); // 返回 false
        });
      });
    }


    // 初始化执行
    $(function () {
      initPage();
      bindEvents();
    });
  });
</script>

<style>
  /* 数值单元格样式 */

  .budget-overview {
    display: flex;
    height: calc(100% - 20px);
    align-items: center;
    font-size: 13px;
  }

  .layui-card {
    width: 100%;
    margin: 0 auto;
    padding: 15px;
  }

  .layui-row {
    border-bottom: 1px solid #c5c2c2;
    align-items: center;
    min-height: 40px;
  }

  .layui-row:last-child {
    border-bottom: none;
  }

  .project-description-row {
    min-height: 160px;
  }

  .project-row-title {
    text-align: center;
    /*font-size: 13px;  或 18px */
    font-weight: bold;
    display: flex;
    align-items: center;
    justify-content: center;
    padding-top: 15px;
  }

  .project-label-cell {
    text-align: right;
    padding-top: 15px;
    /*font-size: 13px;  或 16px */
    /* font-weight: bold; */
  }

  .project-data-display {
    display: flex;
    align-items: center;
    /*font-size: 13px;  或 16px */
    margin-top: 10px;
    border: 1px solid #e6e6e6;
    background-color: #f8f8f8;
    border-radius: 2px;
    word-break: break-all;
    height: 38px;
    line-height: normal;
    padding: 0 10px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .project-description-row .project-data-display {
    min-height: 160px;
    line-height: 1.5;
    padding: 10px;
    white-space: pre-wrap;
    align-items: flex-start;
  }

  .edit-button-column {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding-top: 15px;
  }
</style>